<?php

namespace app\admin\controller;
use app\common\model\Config as ConfigModel;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 酒店管理
 *
 * @icon   fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Hotels extends Backend
{

    protected $hid = null;
    protected $adminId = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->hid = Session::get("admin")["hotelid"];
        $this->adminId = Session::get("admin")["id"];
        $city = db("city")->where(['parentId'=>-1])->select();
        $citylist = db("city")->where("parentId != '-1'")->select();
        //标签管理
        $lbs = db("label")->where(['status'=>'normal'])->select();
        //房属性管理
        $tys = db("type")->where(['status'=>'normal'])->select();
        //房型管理
        $htys = db("htype")->where(['status'=>'normal'])->select();
        $this->assign("labels",$lbs);
        $this->assign("types",$tys);
        $this->assign("htypes",$htys);
        $this->assign("city",$city);
        $this->assign("citylist",$citylist);

    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            $search = $this->request->request("search");
            $search = trim($search);
            $model = model('Hotels');

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            if($this->adminId == 1){
                $total = $model->where('hoteltitle','like','%'.$search.'%')->order($sort, $order)->count();
                $list = $model
                    ->where('hoteltitle','like','%'.$search.'%')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }else{
                $total = $model->where('hoteltitle','like','%'.$search.'%')->where("hid",'in',$this->hid)->order($sort, $order)->count();
                $list = $model
                    ->where('hoteltitle','like','%'.$search.'%')
                    ->where("hid",'in',$this->hid)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $roomdb = db("house");
            foreach ($list as &$v){
                $all = $roomdb->where(['h_id'=>$v['hid']])->count();
                $use = db("order")->where(['hotelid'=>$v['hid']])->where("pay_status = '1' || pay_status = '2'")->count();
                //$v['h_use'] = $use."/".$v['h_guestroom'];
                $v['h_use'] = $use."/".$all;
            }



            $result = array("total" => $total, "rows" => $list);

            return json($result);


        }
        return $this->view->fetch();
    }

    /**
     * 获取酒店列表
     */
    public function getHotels()
    {


        if ($this->request->isAjax()) {
            $model = model('Hotels');
            list($where, $sort, $order) = $this->buildparams();


            if($this->adminId == 1){

                $list = $model->where("h_status='normal'")->field("hid,hoteltitle")->order("hid asc")->select();
            }else{
                $list = $model->where("h_status='normal'")->field("hid,hoteltitle")->where('hid','in',$this->hid)->order("hid asc")->select();
            }




            if($list){
                $result = array("code"=>1,"rows" => $list);
            }else{
                $result = array("code"=>0,"rows" => []);
            }


            return json($result);



        }

    }



    /**
     * 批量更新
     */
    public function multi($ids = "")
    {

        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $model = model('Hotels');
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $model->where("hid", 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {


        if ($ids) {
            $model = model('Hotels');
            $list = $model->where("hid", 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 添加
     */
    public function add()
    {
        $serviceList = [];
        if ($this->request->isPost()) {
            $model = model('Hotels');
            $params = $this->request->post();

            if ($params) {
                $params = $this->preExcludeFields($params);


                if(!empty($params["row"]["h_imgs"])){
                    $imgs = explode(",",$params["row"]["h_imgs"]);
                   $params["row"]["h_img"] = $imgs[0];
                }


                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }


                //标签
                $labels = $params["h_lebals"];
                if($labels[0] != ""){
                    $labelsarr = implode(",",$labels);
                    $params["row"]["h_lebals"] = $labelsarr;
                }else{
                    $params["row"]["h_lebals"] = "";
                }

                //固定根据 “小时卡” 查询对应id 前端用来小时卡排序
                $typeinfo = db("type")->field("id,ttitle")->where(['ttitle'=>'小时卡'])->find();

                //房属性
                $htypes = $params["h_types"];
                if($htypes[0] != ""){
                    $htypesarr = implode(",",$htypes);
                    $params["row"]["h_types"] = $htypesarr;
                    //判断是否支持小时卡
                    if(in_array($typeinfo['id'],$htypes)){
                        $params["row"]["h_parking"] = 1;
                    }else{
                        $params["row"]["h_parking"] = 0;
                    }
                }else{
                    $params["row"]["h_types"] = "";
                    $params["row"]["h_parking"] = 0;
                }



                //房型
                $hhtypes = $params["h_htypes"];
                if($hhtypes[0] != ""){
                    $hhtypesarr = implode(",",$hhtypes);
                    $params["row"]["h_htypes"] = $hhtypesarr;
                }else{
                    $params["row"]["h_htypes"] = "";
                }


/*
                //房间设施
                $serv = $params["h_servs"];
                if($serv[0] != ""){
                    $serarr = implode(",",$serv);
                    $params["row"]["h_servs"] = $serarr;
                }else{
                    $params["row"]["h_servs"] = "";
                }*/

                //商圈
                if(array_key_exists("h_servs",$params)){
                    $serv = $params["h_servs"];
                    if($serv[0] != ""){
                        $serarr = implode(",",$serv);
                        $params["row"]["h_servs"] = $serarr;
                    }else{
                        $params["row"]["h_servs"] = "";
                    }
                }else{
                    $params["row"]["h_servs"] = "";
                }





                $result = false;
                Db::startTrans();

                try {

                    $result = $model->save($params["row"]);


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{

            //获取酒店商圈
         /*   $cate = db('area');
            $res = $cate->where("status='normal' ")->field("id,atitle,cityid,citydid")->select();
            if($res){
                $serviceList = $res;
            }else{
                $serviceList = [];
            }

            $this->assign("serviceList",$serviceList);*/
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {


        $model = model('Hotels');
        $row = $model->get($ids)->toArray();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);

                try {

                    if(!empty($params["row"]["h_imgs"])){
                        $imgs = explode(",",$params["row"]["h_imgs"]);
                        $params["row"]["h_img"] = $imgs[0];
                    }


                    if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                        $params[$this->dataLimitField] = $this->auth->id;
                    }

                    //标签
                    $labels = $params["h_lebals"];
                    if($labels[0] != ""){
                        $labelsarr = implode(",",$labels);
                        $params["row"]["h_lebals"] = $labelsarr;
                    }else{
                        $params["row"]["h_lebals"] = "";
                    }

                    //固定根据 “小时卡” 查询对应id 前端用来小时卡排序
                    $typeinfo = db("type")->field("id,ttitle")->where(['ttitle'=>'小时卡'])->find();

                    //房属性
                    $htypes = $params["h_types"];
                    if($htypes[0] != ""){
                        $htypesarr = implode(",",$htypes);
                        $params["row"]["h_types"] = $htypesarr;
                        //判断是否支持小时卡
                        if(in_array($typeinfo['id'],$htypes)){
                            $params["row"]["h_parking"] = 1;
                        }else{
                            $params["row"]["h_parking"] = 0;
                        }
                    }else{
                        $params["row"]["h_types"] = "";
                        $params["row"]["h_parking"] = 0;
                    }


                    //房型
                    $hhtypes = $params["h_htypes"];
                    if($hhtypes[0] != ""){
                        $hhtypesarr = implode(",",$hhtypes);
                        $params["row"]["h_htypes"] = $hhtypesarr;
                    }else{
                        $params["row"]["h_htypes"] = "";
                    }


                    //商圈
                    if(array_key_exists("h_servs",$params)){
                        $serv = $params["h_servs"];
                        if($serv[0] != ""){
                            $serarr = implode(",",$serv);
                            $params["row"]["h_servs"] = $serarr;
                        }else{
                            $params["row"]["h_servs"] = "";
                        }
                    }else{
                        $params["row"]["h_servs"] = "";
                    }


                    $result = $model->where("hid=$ids")->update($params["row"]);


                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
           /* //酒店商圈
            $cate = db('area');

            $res = $cate->where("status='normal' ")->field("id,atitle,cityid,citydid")->select();
            if($res){
                $serviceList = $res;
            }else{
                $serviceList = [];
            }

            $this->assign("serviceList",$serviceList);*/
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
